package com.sctvcloud.qingchuan.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.beans.AccountNewsItem;
import com.sctvcloud.qingchuan.beans.AccountNewsVo;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.ui.activities.AccountImageDetailActivity;
import com.sctvcloud.qingchuan.ui.activities.AccountNewsDetailActivity;
import com.sctvcloud.qingchuan.ui.activities.AccountVideoDetailActivity;
import com.sctvcloud.qingchuan.ui.adapter.AttentionAdapter;
import com.sctvcloud.qingchuan.ui.adapter.holder.AttentionNewsHolder;
import com.sctvcloud.qingchuan.ui.util.IListShowData;
import com.sctvcloud.qingchuan.ui.utils.DataUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

/**
 * 公众号详情---新闻列表
 */
public class AccountDetailNewsFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, AttentionNewsHolder.OnNewsClickListener {
    @BindView(R.id.refreshlayout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;
    public static final String ACCOUNT_ID = "account_id";
    public static final String NEWS_TYPE = "news_type";
    private int newsType = 0;
    private String accountId = "";
    private AttentionAdapter mAdapter;
    private int mPageNo = 1;
    private boolean mIsLoading = false;
    private int mPageAll = 0;
    private List<IListShowData> dataList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_account_news_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        Bundle arguments = getArguments();
        if (arguments != null) {
            newsType = arguments.getInt(NEWS_TYPE, 0);
            accountId = arguments.getString(ACCOUNT_ID);
        }
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        if (isFirst) {
            mRefreshLayout.autoRefresh();
        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void onLoadMore() {
        mPageNo++;
        getData();
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        dataList.clear();
        mPageNo = 1;
        mIsLoading = true;
        getData();
    }

    /**
     * 设置是否可以下拉刷新
     * @param isEnable
     */
    public void setRefreshLayoutRefreshEnable(boolean isEnable) {
        mRefreshLayout.setRefreshEnabled(isEnable);
    }

    private void getData() {
        if (!TextUtils.isEmpty(accountId)) {
            Map<String, String> formMaildata = new HashMap<>();
            formMaildata.put("tenantId", Constances.TENANT_ID);
            formMaildata.put("page", "" + mPageNo);
            formMaildata.put("pageSize", "10");
            formMaildata.put("type", "" + newsType);
            RequestBody body = DataUtils.toRequestBody(formMaildata);
            String url = "utils/cms/getArticleListByUserId/" + accountId;
            NetUtils.getNetAdapter().getAccountNewsListString(getOwnerName(), url, body, new AbsNetCallBack<String>(String.class) {
                @Override
                public void onSucStr(String news) {
                    if (!TextUtils.isEmpty(news)) {
                        try {
                            AccountNewsVo bean = gson.fromJson(news, AccountNewsVo.class);
                            if (bean != null) {
                                if (mPageAll == 0) {
                                    mPageAll = bean.getPageAll();
                                }
                                dataList.addAll(bean.getNews());
                                initData(dataList);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        onError(null, "数据异常");
                    }
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    toast(errorMsg);
                    if (mPageNo > 1) {
                        mPageNo--;
                    }
                }


                @Override
                public void onEnd() {
                    onNetFinish();
                }
            });
        } else {
            onNetFinish();
        }

    }

    private void initData(List<IListShowData> dataList) {
        if (mAdapter == null) {
            mAdapter = new AttentionAdapter(getActivity(), dataList, null, this);
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.setData(dataList);
        }

    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
        mRefreshLayout.setLoadMoreEnabled(mPageNo >= mPageAll ? false : true);
    }

    @Override
    public void OnItemClick(AccountNewsItem temp) {
        if (temp.getType() == 1) {
            Intent intent = new Intent(getActivity(), AccountNewsDetailActivity.class);
            intent.putExtra(AccountNewsDetailActivity.NEWS_ID, temp.getId());
            getActivity().startActivityForResult(intent, 1);
        } else if (temp.getType() == 5) {
            Intent intent = new Intent(getActivity(), AccountVideoDetailActivity.class);
            intent.putExtra(AccountVideoDetailActivity.NEWS_ID, temp.getId());
            getActivity().startActivityForResult(intent, 1);
        } else if (temp.getType() == 2) {
            Intent intent = new Intent(getActivity(), AccountImageDetailActivity.class);
            intent.putExtra(AccountImageDetailActivity.NEWS_ID,temp.getId());
            getActivity().startActivityForResult(intent,1);
        }

    }


}
